<template>
  <el-dialog
    class="set-project-comp"
    :title="title"
    :close-on-click-modal="false"
    :append-to-body="true"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(900)"
    :before-close="handleCancel"
  >
    <div class="form-container">
      <el-form
        :model="ruleForm"
        :rules="rules"
        size="medium"
        ref="ruleForm"
        class="rule-form"
        :label-width="$setRem(130)"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName" required>
              <el-input
                placeholder="请输入"
                v-model="ruleForm.projectName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目简称" prop="projectAbbreviation" required>
              <el-input
                placeholder="请输入"
                v-model="ruleForm.projectAbbreviation"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="manageName" required>
              <el-input
                placeholder="请输入"
                v-model="ruleForm.manageName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="managePhone" required>
              <el-input
                placeholder="请输入"
                :controls="false"
                v-model="ruleForm.managePhone"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="projectStatus">
              <el-radio-group v-model="ruleForm.projectStatus">
                <el-radio value="1" label="在建工程"></el-radio>
                <el-radio value="2" label="竣工"></el-radio>
                <el-radio value="0" label="停工"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="施工许可证编号" prop="constructionPermitId">
              <el-input
                placeholder="请输入"
                v-model="ruleForm.constructionPermitId"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属机构" prop="orgId">
              <el-select placeholder="请选择所属机构" v-model="ruleForm.orgId">
                <el-option
                  v-for="item in orgList"
                  :key="item.id"
                  :label="item.orgName"
                  :value="item.id"
                >
                  {{ item.orgName }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item
              class="location"
              label="项目定位"
              prop="point"
              required
            >
              <add-location v-model="ruleForm.point"></add-location>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="项目地址" prop="projectAddress">
              <el-input
                placeholder="请输入项目地址"
                v-model="ruleForm.projectAddress"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="项目简介" prop="projectDescription">
              <el-input
                type="textarea"
                placeholder="请输入"
                :rows="3"
                v-model="ruleForm.projectDescription"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="承包模式" prop="contractMode">
              <el-input
                placeholder="请输入"
                v-model="ruleForm.contractMode"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程类别" prop="projectType" required>
              <el-select
                placeholder="请选择工程类别度"
                v-model="ruleForm.projectType"
              >
                <el-option label="房建" value="房建"></el-option>
                <el-option label="市政" value="市政"></el-option>
                <el-option label="安装" value="安装"></el-option>
                <el-option label="装饰" value="装饰"></el-option>
                <el-option label="矿山" value="矿山"></el-option>
                <el-option label="公路" value="公路"></el-option>
                <el-option label="铁路" value="铁路"></el-option>
                <el-option label="水利水电" value="水利水电"></el-option>
                <el-option label="电力" value="电力"></el-option>
                <el-option label="化工石油" value="化工石油"></el-option>
                <el-option label="农林" value="农林"></el-option>
                <el-option label="港口与航道" value="港口与航道"></el-option>
                <el-option label="航天航空" value="航天航空"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="结构类型" prop="buildingStructure">
              <el-select
                placeholder="请选择结构类型"
                v-model="ruleForm.buildingStructure"
              >
                <el-option
                  label="钢筋混凝土结构"
                  value="钢筋混凝土结构"
                ></el-option>
                <el-option label="框架结构" value="框架结构"></el-option>
                <el-option label="剪力墙结构" value="剪力墙结构"></el-option>
                <el-option
                  label="框架-剪力墙结构"
                  value="框架-剪力墙结构"
                ></el-option>
                <el-option label="混合结构" value="混合结构"></el-option>
                <el-option label="筒体结构" value="筒体结构"></el-option>
                <el-option label="钢结构" value="钢结构"></el-option>
                <el-option
                  label="型钢混凝土结构砖混结构"
                  value="型钢混凝土结构砖混结构"
                ></el-option>
                <el-option label="砖木结构" value="砖木结构"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建筑面积" prop="area">
              <el-input-number
                placeholder="请输入"
                :controls="false"
                v-model="ruleForm.area"
              >
              </el-input-number
              >&nbsp;&nbsp;平方米
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="工程用途" prop="projectPurpose">
              <el-input
                placeholder="请输入"
                v-model="ruleForm.projectPurpose"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程造价" prop="projectCost">
              <el-input-number
                placeholder="请输入"
                :controls="false"
                v-model="ruleForm.projectCost"
              >
              </el-input-number
              >&nbsp;&nbsp;万元
            </el-form-item>
          </el-col>
        </el-row>

        <!--合同信息-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同签订日期" prop="signingDate">
              <el-date-picker
                v-model="ruleForm.signingDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="竣工日期" prop="completionDate">
              <el-date-picker
                v-model="ruleForm.completionDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开工日期" prop="commencementDate">
              <el-date-picker
                v-model="ruleForm.commencementDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="合同工期" prop="contractDate">
              <el-date-picker
                v-model="ruleForm.contractDate"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button type="primary" @click="handleCancel">取 消</el-button>
      <el-button
        class="success"
        type="primary"
        :loading="loading"
        @click="hanldeSave"
      >
        保 存
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import addLocation from "@/components/corp/addLocation";

export default {
  components: {
    addLocation
  },
  props: {
    // 弹框是否展示
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object,
      default: () => ({})
    },
    // 新增、编辑
    type: {
      type: String,
      default: "add"
    }
  },
  data() {
    return {
      orgList: [],
      // form表单数据
      ruleForm: {
        uuid: "",
        projectId: "",
        // 项目名
        projectName: "",
        // 项目简称
        projectAbbreviation: "",
        manageName: "",
        managePhone: "",
        // 项目简介
        projectDescription: "",
        // 所属机构
        orgId: "",
        // 状态
        projectStatus: "",
        // 施工许可证编号
        constructionPermitId: "",
        // 工程类别
        projectType: "",
        // 结构类型
        buildingStructure: "",
        // 工程用途
        projectPurpose: "",
        // 工程造价，保留4位小数点
        projectCost: "",
        // 建筑面积，保留4位小数点
        area: "",
        // 合同签订时间
        signingDate: "",
        // 合同开始工期
        commencementDate: "",
        // 合同工期
        contractDate: "",
        // 承包模式
        contractMode: "",
        // 竣工日期
        completionDate: "",
        // 定位点
        point: {
          lng: "",
          lat: "",
          altitude: ""
        },
        // 项目地址
        projectAddress: ""
      },
      // form 表单校验规则
      rules: {
        projectName: [{ required: true, message: "请输入项目名称" }],
        projectAbbreviation: [{ required: true, message: "请输入项目简称" }],
        manageName: [{ required: true, message: "请输入项目经理" }],
        managePhone: [
          { required: true, message: "请输入联系方式" }
          // { message: '手机号格式不对', pattern: /^1[3456789]\d{9}$/, trigger: 'blur' },
        ],
        point: [
          { required: true, message: "请完善定位点信息" },
          { validator: this.pointValidator, trigger: "blur" }
        ],
        projectType: [{ required: true, message: "请选择工程类别" }]
      }
    };
  },
  computed: {
    // 设置弹框标题
    title() {
      return `${this.type === "add" ? "新增" : "编辑"}项目`;
    }
  },
  watch: {
    // 监听回填数据
    options: {
      deep: true,
      handler: function(data) {
        if (this.$checkType(data) === "object") {
          const keys = Object.keys(this.ruleForm);
          keys.forEach(key => {
            const value = data[key];
            // 定位点
            if (key === "point") {
              this.ruleForm[key] = {
                lng: data.lng,
                lat: data.lat,
                altitude: data.altitude
              };
              return;
            }
            if (key === "contractDate") {
              // contractFrom: 合同开始工期 contractTo: 合同结束工期
              this.ruleForm[key] = [
                data.contractFrom ? new Date(data.contractFrom) : "",
                data.contractTo ? new Date(data.contractTo) : ""
              ].filter(val => val);
              return;
            }
            const hasval = ["undefined", "null"].includes(
              this.$checkType(value)
            );
            this.ruleForm[key] = hasval ? "" : value;
          });
        }
      }
    },
    // 监听弹框显示/隐藏
    visible(data) {
      if (!data) {
        Object.keys(this.ruleForm).forEach(key => {
          if (key === "point") {
            this.ruleForm[key] = {
              lng: "",
              lat: "",
              altitude: ""
            };
            return;
          }
          this.ruleForm[key] = "";
        });
      }
      this.getOrgPageList();
    }
  },
  methods: {
    // 获取机构
    async getOrgPageList() {
      const {
        success,
        data: { data }
      } = await this.$Model.getOrgPageList({
        pageFlag: false
      });
      if (success && data) {
        this.orgList = data.list || [];
      }
    },
    /**
     * 校验定位点信息
     * @param rule 校验规则
     * @param value 定位点数据
     * @param callback 校验回调
     */
    pointValidator(rule, value, callback) {
      const check = Object.keys(this.ruleForm.point).some(key => {
        return !value[key] || /^\s+$/.test(value[key]);
      });
      if (check) return callback("请完善定位点信息");
      return callback();
    },
    // 保存
    hanldeSave() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const datekeys = [
            "signingDate",
            "contractDate",
            "commencementDate",
            "completionDate"
          ];
          // 对时间字段调整格式重新赋值
          Object.keys(this.ruleForm).forEach(key => {
            const value = this.ruleForm[key];
            if (datekeys.includes(key) && value) {
              if (Array.isArray(value)) {
                this.ruleForm[key] = value.map(val =>
                  this.$moment(val).format("yyyy-MM-DD HH:mm:ss")
                );
                return;
              }
              this.ruleForm[key] = this.$moment(value).format(
                "yyyy-MM-DD HH:mm:ss"
              );
            }
          });
          const {
            contractDate,
            point = {},
            projectCost,
            area,
            ...others
          } = this.ruleForm;
          const options = {
            ...others,
            // lng: 经度, lat: 纬度, altitude: 海拔
            lng: point.lng ? parseFloat(point.lng).toFixed(6) : "",
            lat: point.lat ? parseFloat(point.lat).toFixed(6) : "",
            altitude: point.altitude
              ? parseFloat(point.altitude).toFixed(4)
              : "",
            area: area ? parseFloat(area).toFixed(4) : "",
            // 工程造价，保留4位小数点
            projectCost: projectCost ? parseFloat(projectCost).toFixed(4) : "",
            // 合同开始工期，时间格式为yyyy-MM-dd hh:mm:ss
            contractFrom: contractDate[0] || "",
            // 合同结束工期
            contractTo: contractDate[1] || ""
          };
          if (this.type === "add") delete options.projectId;
          this.$emit("submit", options);
          return;
        }
        this.$emit("submit", false);
      });
    },
    // 取消
    handleCancel() {
      this.$emit("cancel");
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../../assets/styles/dialog";
.set-project-comp {
  .form-container {
    width: 100%;
    /deep/ .el-form {
      width: 100%;
      padding-right: 30px;
      > .el-row {
        .el-form-item__label {
          color: #fff;
        }
        .el-form-item__content {
          input,
          textarea,
          .el-date-editor {
            background-color: #0e0e2d;
            border: none;
            color: #fff;
            .el-range-separator {
              color: $mainColor;
            }
          }
        }
        .el-radio {
          color: $mainColor;
          &.is-checked {
            .el-radio__label {
              color: #fff;
            }
          }
        }
      }
    }
    /deep/ .el-form-item {
      margin-bottom: 15px;
    }
  }
  .dialog-footer {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .el-dialog__body {
    padding-top: 5px;
  }
}
</style>
